//第28天

package main

import (
	"fmt"
	"time"
)

type Math struct {
	X, Y int
}

func test1(){
	m := map[string]Math {
		"foo":{1,2},
	}
	tmp := m["foo"]
	tmp.X = 4
	m["foo"] = tmp
	fmt.Println(m["foo"])
}

func test2(){
	//数组可以比较
	fmt.Println([1]int{1} == [1]int{1})
	//切片不可以比较
	//fmt.Println([]int{1} == []int{1})
}

func test3(){
	var cl = []int{1,2,3}
	for k, v := range cl {
		//k, v 变量地址是不变的, 思考如果需要当前k, v 在goroutine中要怎么做
		go func(){
			fmt.Println(k, v)
		}()
	}

	//fix
	for k, v :=range cl {
		go func(k, v int){
			fmt.Println(k, v)
		}(k, v)
	}
	time.Sleep(2*time.Second)
}

//神奇的defer
func test4(n int) (r int){

	defer func(){
		r += n
		recover()
	}()

	var f func()
	defer f() //f还未定义 引发panic
	//这句没实际意义了
	f = func(){
		n += 2
	}

	return n + 1
}

func test5(){
	a := [5]int{1,2,3,4,5}
	r := [5]int{}
	for k, v := range a {
		if k == 0 {
			a[1] = 12
			a[2] = 13
		}
		r[k] = v
	}
	fmt.Printf("r:%v\n", r)
	fmt.Printf("a:%v\n", a)

	//rr := []int{} //空切片不能赋值
	//rr[0] = 1
	//fmt.Println(rr)
}

func test6(s ...int){
	fmt.Printf("s:%v\n", &s[0])
	s = append(s, 3)
	fmt.Printf("s:%v\n", &s)
}

//赋值从右边开始
func test7(){
	i := 1
	s := []string{"A", "B", "C"}
	i, s[i-1] = 2, "Z"
	fmt.Println("s:", s)
}

func main() {
	fmt.Println("沧浪之水")
	test1()
	test2()
	test3()

	a := test4(3)
	fmt.Println("test4:",a)

	test5()

	s1 := []int{0, 1, 2, 3, 8: 100} // 通过初始化表达式构造，可使用索引号。
	fmt.Println(s1, len(s1), cap(s1))

	slice := make([]int, 5, 5)
	slice[0] = 1
	slice[1] = 2
	test6(slice...)
	fmt.Println(slice)
	fmt.Printf("s:%v\n", &slice[0])

	test7()

}